import { Inject, Middleware, httpError } from '@midwayjs/core';
import { JwtService } from '@midwayjs/jwt';
import { Context, NextFunction } from '@midwayjs/koa';

@Middleware()
export class JwtMiddleware {
  @Inject()
  jwtService: JwtService;

  public static getName(): string {
    return 'jwt';
  }

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 认证身份信息判断 获取
      if (!ctx.header['authorization']) {
        throw new httpError.UnauthorizedError();
      }
      const parts = ctx.get('authorization').trim().split('  ');
      if (parts.length !== 2) {
        throw new httpError.UnauthorizedError();
      }
      const [scheme, token] = parts;

      if (/^Bearer$/i.test(scheme)) {
        // 验证token是否合法
        await this.jwtService.verify(token, {
          complete: true,
        });
        await next();
      }
    };
  }
  // 配置忽略认真校验的路由地址

  public match(ctx: Context): boolean {
    const ignore = ['/auth/register', '/auth/login'].includes(ctx.path);
    return !ignore;
  }
}
